package com.sz.framework.log.slf4j;

import com.sz.framework.log.SzLog;
import com.sz.framework.log.slf4j.enums.LoggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 日志工厂-根据运行环境自动检测使用的日志实现框架
 *
 * @author: yxl
 * 2025-07-24
 */
public class SzLogFactory {

    private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);
    private static volatile LoggerImpl detectedImpl = LoggerImpl.UNKNOWN;

    static {
        detectLoggerImpl();
    }

    public static SzLog getLogger(Class<?> clazz) {
        return new SzLogToSlf4jAdapter(clazz);
    }

    public static SzLog getLogger(String name) {
        return new SzLogToSlf4jAdapter(name);
    }

    /**
     * 检测运行时日志实现
     */
    private static void detectLoggerImpl() {
        if (!INITIALIZED.compareAndSet(false, true)) {
            return;
        }

        try {
            // 检测 Logback
            Class.forName("ch.qos.logback.classic.Logger");
            if (isLogbackAvailable()) {
                detectedImpl = LoggerImpl.LOGBACK;
                return;
            }
        } catch (ClassNotFoundException e) {
            // Logback 不可用
        }

        try {
            // 检测 Log4j2
            Class.forName("org.apache.logging.log4j.core.Logger");
            if (isLog4j2Available()) {
                detectedImpl = LoggerImpl.LOG4J2;
                return;
            }
        } catch (ClassNotFoundException e) {
            // Log4j2 不可用
        }

        // 默认未知
        detectedImpl = LoggerImpl.UNKNOWN;
    }

    /**
     * 检查 Logback 是否可用
     *
     * @return 是否可用
     */
    private static boolean isLogbackAvailable() {
        try {
            // 尝试创建 Logback Logger 来验证可用性
            Logger logger = LoggerFactory.getLogger(SzLogFactory.class);
            // 检查实际的实现类
            String loggerClassName = logger.getClass().getName();
            return loggerClassName.contains("ch.qos.logback");
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查 Log4j2 是否可用
     *
     * @return 是否可用
     */
    private static boolean isLog4j2Available() {
        try {
            // 尝试创建 Log4j2 Logger 来验证可用性
            Logger logger = LoggerFactory.getLogger(SzLogFactory.class);
            // 检查实际的实现类
            String loggerClassName = logger.getClass().getName();
            return loggerClassName.contains("org.apache.logging.log4j");
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取检测到的日志实现类型
     *
     * @return 日志实现类型
     */
    public static LoggerImpl getDetectedImplementation() {
        return detectedImpl;
    }


}
